
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#define N 256


int main(int argc , char **argv)
{

int fsrc , fdst;
struct stat fileStat;
size_t toread = N;
ssize_t towrite , written;
char buffer[N];	
char *src , *dst;

int x;

src = "Folder_di_copia/file_da_copiare";
dst = "Folder_di_copia/File_di_prova";

if((fsrc = open(src , O_RDONLY)) == -1)
	{
	printf("Errore apertura file sorgente %s" , src);
	return -1;
	}

fstat(fsrc , &fileStat);

if((fdst = open(dst , O_CREAT | O_WRONLY | O_EXCL)) == -1)
	{	
	if(errno == EEXIST)
		{
		printf("Il file %s è già esistente, vuoi sovrascriverlo y/n \n", src);
		char r , s;
		scanf("%c" , &r);
		while(r != 'y' && r!='n'){
			scanf("%c" , &s);
			printf("Input accettati y/n \n");
			scanf("%c" , &r);	
		}
		if(r == 'n') 
		{ 
		printf("File non copiato\n");
		close(fsrc); 
		return -1;
		}
		else
		if((fdst = open(dst , O_CREAT | O_WRONLY)) == -1)
		{
		printf("Errore apertura file destinazione %s " , dst);
		return -1;
		}}
	}
	
fchmod(fdst , fileStat.st_mode);

towrite = read(fsrc , buffer , toread);
written = write(fdst , buffer , towrite);

printf("read = %d \n" ,(int)   towrite);
printf("write = %d \n" , (int) written);
	
	
close(fsrc);
close(fdst);

return 0;
}





